package com.tgl.util;

import com.tgl.scheduler.PingScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.Optional;

/**
 * @author tonggulin
 * @description: 文件锁工具类
 * @date 2024/7/28 21:09
 */
public class FileLockUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileLockUtil.class);

    public static FileLock getLock(File lockFile) throws FileNotFoundException {
        FileOutputStream fos;
        FileChannel channel = null;
        fos = new FileOutputStream(lockFile);
        channel = fos.getChannel();

        try {
            if (channel!=null) {
                return channel.tryLock();
            }
        } catch (OverlappingFileLockException e) {
            logger.info("file has been used, {}", e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return null;
    }


    public static void releaseLock(FileLock fileLock) {
            try {
                fileLock.release();
            } catch (Exception ex) {
                logger.error(ex.getMessage());
            }
    }
}
